import Cocoa
import Foundation
import FlutterMacOS

public class AppupgradePlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "appupgrade", binaryMessenger: registrar.messenger)
    let instance = AppupgradePlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "runDmg":
        guard let argument = call.arguments as? [String: Any?] else {
          result(FlutterError(code: "0", message: "arg is not map", details: nil))
          return
        }
        let task: Process = Process()
        task.launchPath = "/bin/bash"
        let path = argument["path"] as? String ?? ""
//        let name = path.components(separatedBy: ["/"]).last ?? ""
//        let dir = path.replacingOccurrences(of: name, with: "")
        task.arguments = ["-c", "open \(path)"]
        let pipe: Pipe = Pipe()
        task.standardOutput = pipe
        let file = pipe.fileHandleForReading
        task.launch()
        let data = file.readDataToEndOfFile()
        result(String(data: data, encoding: .utf8))
        break;
    default:
      result(FlutterMethodNotImplemented)
    }
  }
}
